package com.lulin.mall.cart.interceptor;

import com.lulin.common.constant.AuthConstant;
import com.lulin.common.vo.MemberVo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义的拦截器：帮助我们获取当前登录的用户信息
 * 通过Session共享获取的
 *
 * @author lulin
 * @date 2022/12/14 14:59
 */
public class AuthInterceptor implements HandlerInterceptor {
    //本地线程对象：  其实是一个map容器 Map<thread,Object>
    public static ThreadLocal<MemberVo> threadLocal = new ThreadLocal();

    /**
     * 会在控制器触发之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return true 不做拦截处理，只做数据认证处理
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过httpSession，获取当前登录的用户信息
        HttpSession session = request.getSession();
        Object attribute = request.getSession().getAttribute(AuthConstant.AUTH_SESSION_REDIS);
        if (attribute != null) {
            MemberVo memberVo = (MemberVo) attribute;
            threadLocal.set(memberVo);
            return true;
        }
        //如果 attribute =null，说明没有登录，要重定向到登录页面
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG,"请先登录");
        response.sendRedirect("http://auth.lulin.com/login.html");
        return false;
    }
}
